package com.bsoft.gol.editor.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Controller基类
 * 
 * @author Administrator
 *
 */

@Controller
public class ApiBaseController {

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

	/**
	 * 获取UID，用户ID
	 * 
	 * @param request
	 * @return
	 */
	public Long getUid(HttpServletRequest request) {
		Object uid = request.getAttribute("id");
		if(uid==null){
			uid=request.getParameter("userId");
		}
		if(uid == null) {
			uid = getJsonParameter(request, "userId");
		}
		return null != uid ? Long.valueOf(uid.toString()) : null;
	}

	public Object getJsonParameter(HttpServletRequest request, String name) {
		Object result= null; 
		try {
			BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
			StringBuilder responseStrBuilder = new StringBuilder();
			String inputStr;
			while ((inputStr = streamReader.readLine()) != null)
				responseStrBuilder.append(inputStr);
			
			JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
			if(jsonObject!=null){
				result = jsonObject.get(name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
